﻿using System;
using System.Collections.Generic;
using Framework.Business;
using Framework.Helper;
using MongoDB.Driver;
using RealDataReceiver.Entities;

namespace RealDataReceiver.DataAccess
{
    public interface IAlarmDA
    {
        void SaveMany(List<AlarmMetaData> metaDataList);
        void Update(string alarmid, string status);
        IMongoCollection<AlarmMetaData> GetCollection();
    }
    public class AlarmDA : IAlarmDA
    {
        private readonly IMongoCollection<AlarmMetaData> _mongoAlarmCollection;
        private AlarmDA()
        {
            var client = new MongoClient(ConfigurationHelper.GetConfiguration("ConnectionString"));
            var database = client.GetDatabase(ConfigurationHelper.GetConfiguration("DBInstance"));
            _mongoAlarmCollection = database.GetCollection<AlarmMetaData>(ConfigurationHelper.GetConfiguration("AlarmCollection"));
        }

        static AlarmDA()
        {
            InstanceManager.RegisterBuilder<IAlarmDA, AlarmDA>(() => new AlarmDA());
        }

        public static IAlarmDA Instance
        {
            get { return InstanceManager.GetInstance<IAlarmDA>(); }
        }

        public IMongoCollection<AlarmMetaData> Collection
        {
            get { return _mongoAlarmCollection; }
        }

        public void SaveMany(List<AlarmMetaData> metaDataList)
        {
            try
            {
                _mongoAlarmCollection.InsertMany(metaDataList);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public void Update(string alarmid, string status)
        {
            _mongoAlarmCollection.FindOneAndUpdate(e => e.AlarmId == alarmid,
                Builders<AlarmMetaData>.Update.Set(e => e.Status, status));
        }

        public IMongoCollection<AlarmMetaData> GetCollection()
        {
            return _mongoAlarmCollection;
        }
    }
}
